package com.atguigu.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.atguigu.base.BaseController;
import com.atguigu.entity.HouseImage;
import com.atguigu.result.Result;
import com.atguigu.service.HouseImageService;
import com.atguigu.util.QiniuUtil;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

@Controller
@RequestMapping("/houseImage")
public class HouseImageController extends BaseController {
    @Reference
    private HouseImageService houseImageService;


    @RequestMapping("/uploadShow/{houseId}/{type}")
    public String uploadShow(@PathVariable Long houseId, @PathVariable Integer type, Model model){
        model.addAttribute("houseId",houseId);
        model.addAttribute("type",type);
        //转发到一个上传页面的窗口
        return "houseImage/upload";
    }

    //上传页面的handler
    ///houseImage/upload/[[${houseId}]]/[[${type}]]

    @RequestMapping("/upload/{houseId}/{type}")
    @ResponseBody
    public Result upload(@PathVariable Long houseId, @PathVariable Integer type, @RequestParam(value = "file") MultipartFile[] files) throws IOException {
        if(files!=null){
            for (MultipartFile file : files) {
                //1.上传图片到七牛云
                //1.1上传需要处理图片名称,不能重名因此需要加uuid,需要文件后缀所以需要剪切原文件名.
                String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
                String fileName = UUID.randomUUID().toString()+suffix;
                QiniuUtil.upload2Qiniu(file.getBytes(),fileName);
                //2.上传图片数据到数据库
                HouseImage houseImage = new HouseImage();
                houseImage.setHouseId(houseId);
                houseImage.setType(type);
                houseImage.setImageUrl("http://skizgp4uh.hn-bkt.clouddn.com/"+fileName);
                houseImage.setImageName(fileName);
                houseImageService.insert(houseImage);
            }
        }

        return Result.ok();
    }


    @RequestMapping("/delete/{houseId}/{id}")
    public String delete(@PathVariable Long houseId,@PathVariable Long id){
        //id为被删除图片主键id
        //1.删除七牛云上的图片
        //1.1 传入的只有数据库中的图片主键,我们需要图片name才能去七牛云删除,所以这里需要查询
        HouseImage houseImage = houseImageService.getById(id);
        QiniuUtil.deleteFileFromQiniu(houseImage.getImageName());
        //2.删除数据库中的图片信息
        houseImageService.delete(id);

        return "redirect:/house/"+houseId;
    }

}
